package service.encryption;

import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class Encrypter implements IEncrypter{
	
	private MessageDigest msgDigest;
	private String algorithme="SHA-1";
	private byte[] hash;	

	public String getAlgorithme(){
		return algorithme;
	}

	public void setAlgorithme(String algorithme){
		this.algorithme = algorithme;
	}
	
	public String encrypte(String password) throws Exception {
		   
		try{        	 	   
		    msgDigest=MessageDigest.getInstance(getAlgorithme());
			msgDigest.update(password.getBytes());
			hash=msgDigest.digest();
			
			return bytes2String(hash);
		}
		catch(NoSuchAlgorithmException x){
		   throw new Exception("Impossible de continuer la hashage du mot");
		}
		
	}
	private static String bytes2String(byte[] bytes) {
	    StringBuilder string = new StringBuilder();
	    for (byte b : bytes) {
	        String hexString = Integer.toHexString(0x00FF & b);
	        string.append(hexString.length() == 1 ? "0" + hexString : hexString);
	    }
	    return string.toString();
	}
}